#!/bin/bash
# ADORE
# Automatic Doris Environment
# 
# USAGE:
# 	adore adoreCommand
#	adore -u user.set adoreCommand 
#	adore -u user.set -p dorisProcess
#	adore -u user.set -p dorisProcess adoreCommand
#	adore -v -p dorisProcess -d "adoreVariable1=Value1;adoreVariable2=Value2"
#	adore -i 
#	adore -g filename
#	adore -V
#
# DESCRIPTION:
#	ADORE is an attempt to simplify processing of different interferometric stacks
#  like, single-master-stack, or short-baselines.
# default options are loaded from ${ADOREFOLDER}/set/default.set
# each doris step can be run. They should have a corresponding *.drs file in the drs folder.
# 
# INPUT:
#  adoreCommand: see the manual for available adoreCommands
#  -u: user settings file. 
#  -p: process Doris step. (m_readfiles, s_readfiles, interfero...)
#  -d: define variable (has priority over user settings file.)
#  -i: open interactive session. 
#  -g: filename for ADORE-GUI. This is useless if you are not using ADORE-GUI.
#  -v: verbose. For troubleshooting. Equivalent to: set -x
#  -V: Version. Print ADORE version and exit.
#
# if both adoreCommand and dorisProcess is used, first the dorisProcess
# is run, and then the adoreCommand.
#
# OUTPUT:
#  nothing for adoreCommands.
#  dorisStep: SUCCESS for successful doris processing steps.
#

#NOT NECESSARY WITH CHILD BASH PROCESS
#ctrl_c()
#{
## if [ "${ctrl_c_counter-0}" -lt "1" ]; then 
#   #ctrl_c_counter=`expr ${ctrl_c_counter} + 1`
#   #bind redraw-current-line   
#   echo -n "^C"
#   continue
#   #return 0
## else
##   echo " "
##   echo "Saving History..."
##   history -w ${adoreHistoryFile}
##   exit 0;
## fi
#}

if [ "${1-allEmpty}" == "allEmpty" ]; then
  sed -n -e '/^# USAGE:/,/^$/ s/^# \?//p' < ${0}
  exit 0
fi


###### GET INPUT OPTIONS
#start a loop for getopts. I want to read parameters of options -n -i  etc. 
while getopts  "ivVg:u:p:d:" flag
do
  #echo "$flag" $OPTIND $OPTARG 
  # above line outputs the parameter flag (-n, etc.), 
  #index of the flag in the commandline and  the argument. If you just want
  #a flag then you simply remove the column from getopts line 
  #(i.e. to make n a flag "ni:a:...")  
  eval export ${flag}=${OPTARG}
done
# now $u=userSettings, $p=dorisProcess, $d=defineVariables
#below I use a for loop to remove already parsed parameters 
for ((k=1; k<$OPTIND; k++ ))
do
  shift
done  
unset flag OPTARG OPTIND
if [ "${v-notVerbose}" != "notVerbose" ]; then
  set -x
fi

# now I can assign values to the leftover parameters. 
# Need to export the variables to make them available in interactive subshell
export adoreCommand=$1
export dorisProcess=$p

if [ "${ADORESCR:-isEmpty}" = "isEmpty" ]; then
  #Two methods to find ADORE path 
  #LSOF is capable of following links. But not available on all systems
  #dirname method can not follow links causing trouble when adore is a link. 
  LSOF=$(lsof -p $$ | grep -E "/"$(basename $0)"$") # get the location of running script
  if [ $? -ne 0 ]; then 
   ADORESCR=`echo $(cd $(dirname ${0}); pwd -P)`
   if [ -d ${ADORESCR}/fun ]; then 
     export ADORESCR
   else
     echo "ADORE could not define ADORESCR. Please set it as environment variable and retry. ex: export ADORESCR=/opt/adore/scr"
     exit
   fi
  else
    export ADORESCR=$(dirname ${LSOF##* })
  fi
fi
echo ADORESCR=${ADORESCR}
#adjust path in /ADORESCR/.adore.rc, only if interactive
#export _ADOREPATH=${PATH}:${ADORESCR}
if [ "${V-printVersion}" != "printVersion" ]; then
  echo "Version=$(cat ${ADORESCR}/../version )"
  exit
fi

if [ "${i-notInteractive}" != "notInteractive" ]; then
  #interactive - start shell
  bash --init-file "${ADORESCR}/.adore.rc"
#  set -o emacs
#  set -o histexpand
#  HISTCONTROL=ignoreboth
#  #set bind-tty-special-chars off
#  #bind TAB:complete
#  #bind '"TAB":complete-variable'  
#  #bind '"M-[A":history-search-backward'
#  #bind '"M-[B":history-search-forward'
#  #ctrl-r is reverse search history... bind Control-r:redraw-current-line
#  #adoreHistoryFile=${ADOREFOLDER}/scr/.history
#  #INPUTRC=${ADOREFOLDER}/scr/.inputrc
#  [ -e "/etc/bash_completion" ] && source /etc/bash_completion
#  [ -e "${ADOREFOLDER}/scr/.inputrc" ] && source ${ADOREFOLDER}/scr/.inputrc
# #  bind -f ${ADOREFOLDER}/scr/.bind
#  
#  history -r ${adoreHistoryFile}
#  while [ 1 ]; do
#    #PS1='ADORE: '
#    #echo -n "ADORE: "
#    #ctrl_c_counter_bck=${ctrl_c_counter}
#    read -r -p "ADORE: " -e command
#    [ -n "${command}" ] && history -s "${command}"  #add command to history if not empty
#    #echo TEST: ${command%% *} #get the first word.
#    case "${command%% *}" in 
#      exit)
#        history -w ${adoreHistoryFile} #save history
#        exit 0
#        ;;
#      \?)
#        if [ "${command#* }" == "?" ]; then
#          sed -n -e '/^# USAGE:/,/^$/ s/^# \?//p' < "${ADORESCR}/fun/?"
#          continue;
#        fi
#        h ${command#* }      
#        ;;
#      *)
#        eval ${command}
#        ;;
#    esac
#    #I'm placing the trap counter in the loop
#    #so that if a script changes the trap, when
#    #we are back to adore it goes back to ADORE's trap.
#    #trap ctrl-c and call ctrl_c()
#    trap ctrl_c 2 # ctrl+c=sigint 2
#  done
else
  #not interactive - batch processing
  source ${ADORESCR}/.adore.rc
fi

exit 0
